package nina.yiyou.performance.s20confirm.output

import nina.yiyou.salary.input.util.ExcelReadOpener
import org.apache.poi.ss.usermodel.Sheet

import java.nio.file.Files
import java.nio.file.Path

class PerformGeneratePreparer<K> {

  PerformGeneratePreparer(Path templatePath, Closure<K> keyReader, Path outDir, Path tmpDir) {
    _templatePath = templatePath
    _keyReader = keyReader
    _outDir = outDir
    _tmpDir = tmpDir
  }

  K prepare() {
    assert Files.isRegularFile(_templatePath)
    K resultKeys = readResultKeys()
//    println(resultKeys)

    Files.createDirectories(_outDir)

    _tmpDir.deleteDir()
    Files.createDirectories(_tmpDir)

    return resultKeys
  }

  private K readResultKeys() {
    def workbook = new ExcelReadOpener(_templatePath).openXlsx()
    Sheet sheet = workbook.getSheet('data')
    try {
      return _keyReader.call(sheet)
    } finally {
      workbook.close()
    }
  }

  private final Path _templatePath
  private final Closure<K> _keyReader

  private final Path _outDir
  private final Path _tmpDir
}
